package cn.com.open.itembank.service.impl;

import cn.com.open.itembank.dto.OperateDescription;
import cn.com.open.itembank.entity.OperateLog;
import cn.com.open.itembank.mapper.OperateLogMapper;
import cn.com.open.itembank.service.OperateLogService;
import cn.com.open.itembank.utils.DateUtil;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by lucky on 2017/7/20.
 */
@Service("operateLogService")
public class OperateLogServiceImpl implements OperateLogService {

    private static final Logger logger = LoggerFactory.getLogger(OperateLogServiceImpl.class);

    @Autowired
    private OperateLogMapper mapper;

    /**
     * 保存日志.
     *
     * @param operateDescription 操作日志描述对象
     * @param consumeTime        持续时间
     */
    @Override
    public void saveLog(OperateDescription operateDescription, long consumeTime) {
        OperateLog operateLog = makeLog(operateDescription, consumeTime);
        savaLogModel(operateLog);
    }

    /**
     * 日志保存.
     *
     * @param model 操作日志模型
     * @return the boolean
     */
    private void savaLogModel(OperateLog model) {
        try {
            //mapper.insert(model);
            logger.info(new Gson().toJson(model));
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
    }

    /**
     * 创建操作日志类.
     *
     * @param operateDescription the operate description
     * @param consumeTime        the consume time
     * @return the operate log
     */
    private OperateLog makeLog(OperateDescription operateDescription, long consumeTime) {
        //带有占位符的OptDescription
        String description = operateDescription.getDescription();
        if (description.length() > 0) {
            description = description + "|";
        }
        description += "Action监控：ControllerName：%s|ActionName:%s|总时间：%s ms|Action参数：%s|Http请求头:%s|客户端IP：%s|HttpMethod:%s";
        String duration = String.valueOf(consumeTime);
        //对应点位符填充值的数组
        Object[] arr = {operateDescription.getControllerName(),
                operateDescription.getActionName(),
                duration,
                operateDescription.getActionParam(),
                operateDescription.getHttpHeader(),
                operateDescription.getCustomIp(),
                operateDescription.getMethod()};
        //对其进行填充
        String optDescription = String.format(description, arr);
        //创始OperateLog实体，调用数据库insert
        return new OperateLog(operateDescription.getOptUrl(),
                operateDescription.getControllerName(),
                operateDescription.getActionName(),
                operateDescription.getOptType(),
                DateUtil.getCurrentTimeToShowString(),
                operateDescription.getCustomIp(),
                optDescription);
    }
}
